package com.yanqu.road.server.manger.player;

import com.yanqu.road.connect.ServerLinkControl;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.banquet.UserCrossBanquetData;
import com.yanqu.road.entity.enums.*;
import com.yanqu.road.entity.message.WorldMessage;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.entity.servercenter.CrossServerGroup;
import com.yanqu.road.entity.servercenter.ServerGroup;
import com.yanqu.road.entity.servercenter.group.CrossMarriageGroup;
import com.yanqu.road.entity.systemgroup.common.SystemServerGroupWeekData;
import com.yanqu.road.logic.bussiness.message.MessageBussiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.logic.helper.ActivityHelper;
import com.yanqu.road.logic.helper.UnionActivityGroupHelper;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.logic.thread.ThreadTaskManger;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.activity.CommonTeamProto;
import com.yanqu.road.pb.activity.douluodalu.DouLuoDaLuProto;
import com.yanqu.road.pb.banquet.CrossBanquetProto;
import com.yanqu.road.pb.cross.activity.CrossActivityProto;
import com.yanqu.road.pb.cross.group.CrossGroupProto;
import com.yanqu.road.pb.dunhuangshiku.DunHuangShiKuProto;
import com.yanqu.road.pb.kuang.Kuang;
import com.yanqu.road.pb.player.PlayerProto;
import com.yanqu.road.pb.union.cross.CrossUnionProto;
import com.yanqu.road.pb.wingroom.WingRoomProto;
import com.yanqu.road.pb.worldmessage.WorldMessageProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.kuang.KuangModule;
import com.yanqu.road.server.gameplayer.module.xiaomian.XiaoMianModule;
import com.yanqu.road.server.logic.thread.ChatTask;
import com.yanqu.road.server.logic.thread.InnerWoldChatTask;
import com.yanqu.road.server.logic.thread.WoldChatTask;
import com.yanqu.road.server.manger.*;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.activity.RelationActivityMgr;
import com.yanqu.road.server.manger.activity.TradeWarActivityMgr;
import com.yanqu.road.server.manger.activity.chat.ActivityChatMgr;
import com.yanqu.road.server.manger.activity.jiuzhou.JiuZhouMgr;
import com.yanqu.road.server.manger.activity.orewar.OreWarActivityMgr;
import com.yanqu.road.server.manger.activity.strongholdwar.StrongholdActivityMgr;
import com.yanqu.road.server.manger.activity.tonbing.TonBingMgr;
import com.yanqu.road.server.manger.activity.tonbingchannel.ChannelTonBingMgr;
import com.yanqu.road.server.manger.activity.unionwar.UnionWarActivityMgr;
import com.yanqu.road.server.manger.banquet.CrossBanquetMgr;
import com.yanqu.road.server.manger.kuang.KuangMgr;
import com.yanqu.road.server.manger.systemgroup.CrossSystemGroupMgr;
import com.yanqu.road.server.manger.union.CrossUnionMgr;
import com.yanqu.road.server.manger.union.GameUnionActivityGroupMgr;
import com.yanqu.road.server.manger.zhaoshang.ZsMgr;
import com.yanqu.road.server.pb.PlayerPb;
import com.yanqu.road.server.pb.WorldMessagePb;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.ConfigHelper;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.executor.GeneralTask;
import com.yanqu.road.utils.string.StringUtils;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

public class WorldMessageMgr extends TempMgr {

    private static List<WorldMessageProto.WorldMessageTempMsg.Builder> worldMessageMsgList;

    private static List<WorldMessageProto.WorldMessageTempMsg.Builder> systemMessageMsgList;

    private static Map<String, List<WorldMessageProto.WorldMessageTempMsg.Builder>> unionMessageMsgMap;

    private static Map<String, List<WorldMessageProto.WorldMessageTempMsg.Builder>> banquetMessageMsgMap;

    private static ThreadTaskManger threadTaskManger;

    private static AtomicInteger taskId = new AtomicInteger(1);

    public static final int MAX_MESSAGE_COUNT = 50;

    /**
     * 世界聊天频道-记录限制
     */
    public static final int MAX_WORLD_MESSAGE_COUNT = 500;

    public static final String SEPARATOR = "&#!";

    private static Map<Integer, WorldMessage> worldMessageMap;

    private static int msgIndex;

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean save() {
        List<WorldMessage> dataList = new ArrayList<>(worldMessageMap.values());
        for(WorldMessage worldMessage : dataList){
            if(worldMessage.isInsertOption()){
                MessageBussiness.addWorldMessage(worldMessage);
            }else if(worldMessage.isUpdateOption()){
                MessageBussiness.updateWorldMessage(worldMessage);
            }
        }
        return true;
    }

    @Override
    public boolean stop() {
        return false;
    }

    @Override
    public boolean reloadData() {
        systemMessageMsgList = new ArrayList<>();
        worldMessageMap = MessageBussiness.getWorldMessageMap();
        initWorldMessageMsg();
        unionMessageMsgMap = new ConcurrentHashMap<>();
        banquetMessageMsgMap = new ConcurrentHashMap<>();
        if(null == threadTaskManger) {
            threadTaskManger = new ThreadTaskManger(2, "WorldMessageTaskManger");
        }
        taskId = new AtomicInteger(1);
        return true;
    }

    private static void initWorldMessageMsg(){
        List<WorldMessageProto.WorldMessageTempMsg.Builder> msgList = new ArrayList<>();
        List<WorldMessage> messageList = new ArrayList<>(worldMessageMap.values());
        messageList.sort((o1, o2) -> (int) (o1.getSendTime() - o2.getSendTime()));
        for(WorldMessage worldMessage : messageList){
            WorldMessageProto.WorldMessageTempMsg.Builder msg = WorldMessagePb.parseWorldMessageTempMsg(worldMessage);
            if(null != msg){
                msgList.add(msg);
                msgIndex = worldMessage.getIndex() + 1;
            }
        }
        worldMessageMsgList = msgList;
    }

    public static List<WorldMessageProto.WorldMessageTempMsg.Builder> getWorldMessageMsgList(){
        return new ArrayList<>(worldMessageMsgList);
    }

    public static List<WorldMessageProto.WorldMessageTempMsg.Builder> getSystemMessageMsgList() {
        return new ArrayList<>(systemMessageMsgList);
    }

    public static List<WorldMessageProto.WorldMessageTempMsg.Builder> getUnionMessageMsgList(String unionUid){
        if(!StringUtils.isNullOrEmpty(unionUid)){
            List<WorldMessageProto.WorldMessageTempMsg.Builder> dataList = unionMessageMsgMap.get(unionUid);
            if(null != dataList){
                return new ArrayList<>(dataList);
            }
        }
        return null;
    }

    public static Map<String, List<WorldMessageProto.WorldMessageTempMsg.Builder>> getBanquetMessageMsgList(){
        return new HashMap<>(banquetMessageMsgMap);
    }

    /**
     * 玩家聊天
     */
    public static void addWorldMessage(GamePlayer player, WorldMessageProto.WorldMessageTempMsg.Builder msg) {
        if(msg.getType() == eMessageType.WorldChat.getValue() || msg.getType() == eMessageType.WingRoomWorldShare.getValue()) {
            long serverId = ConfigHelper.getLong("serverId");
            if(CrossUnionServerGroupMgr.getGroupServerCountByServerId(serverId) > 1){
                //如果是开启跨服商会分组，则发送到系统分组聊天频道
                msg.setActivityId(eSystemId.Union.getValue());
                sendSystemGroupChat(msg);
            }else {
                //世界聊天
                addWorldMessageMsgToList(msg.getUserId(), msg);
            }
            player.notifyListener(eGamePlayerEventType.ChatActivity.getValue(), msg.getContent());
        }else if(msg.getType() == eMessageType.UnionChat.getValue() || msg.getType() == eMessageType.WingRoomUnionShare.getValue() || msg.getType() == eMessageType.SpringBanquetOpen.getValue()){
            sendUnionChat(player, msg);
        }else if(msg.getType() == eMessageType.CrossActivityChat.getValue() ||
                msg.getType() == eMessageType.EnterNameActivityChat.getValue() || msg.getType() == eMessageType.EnterNameActivityGroupChat.getValue()){
            sendCrossActivityChat(msg);
        }else if(msg.getType() == eMessageType.BanquetChat.getValue()){
            sendBanquetChat(msg);
        }else if(msg.getType() == eMessageType.CrossGroupChat.getValue() || msg.getType() == eMessageType.CrossGroupUnionRecruit.getValue()){
            sendCrossGroupChat(msg);
        }else if(msg.getType() == eMessageType.CrossBanquetChat.getValue()){
            sendCrossBanquetChat(msg);
        }else if(msg.getType() == eMessageType.UnionBussiness.getValue()){
            sendUnionChat(player, msg);
        }else if(msg.getType() == eMessageType.UnionBargain.getValue()){
            sendUnionChat(player, msg);
        }else if(msg.getType() == eMessageType.UnionTradeMsg.getValue()){
            sendUnionChat(player, msg);
        }else if(msg.getType() == eMessageType.ZhaoShangGroupChat.getValue()){
            sendZhaoShangGroupChat(msg);
        }else if(msg.getType() == eMessageType.CrossMarriageGroupChat.getValue()){
            sendCrossMarriageGroupChat(msg);
        }else if(msg.getType() == eMessageType.DunHuangShiKuTeamChat.getValue()){
            sendDunHuangShiKuTeamChat(player,msg);
        }else if(msg.getType() == eMessageType.DouLuoDaLuTeamChat.getValue()){
            sendDouLuoDaLuTeamChat(player,msg);
        }else if(msg.getType() == eMessageType.SystemGroupChat.getValue()){
            sendSystemGroupChat(msg);
        } else if (eMessageType.TongBingPublicChat.getValue() == msg.getType()
                || eMessageType.TongBingCampChat.getValue() == msg.getType()
                || eMessageType.TongBingBattlefieldChat.getValue() == msg.getType()) {
            sendTongBingChat(msg);
        } else if (eMessageType.ChuHanPublicChat.getValue() == msg.getType()
                || eMessageType.ChuHanCampChat.getValue() == msg.getType()
                || eMessageType.ChuHanBattlefieldChat.getValue() == msg.getType()) {
            sendChuHanChat(msg);
        } else if (eMessageType.TonBingPublicChat.getValue() == msg.getType()
                || eMessageType.TonBingCampChat.getValue() == msg.getType()
                || eMessageType.TonBingBattlefieldChat.getValue() == msg.getType()) {
            ActivityInfo activityInfo = TonBingMgr.getActivityInfo();
            if(ActivityMgr.activityInShowTime(activityInfo)){
                sendTonBingChat(msg);
            }
            ActivityInfo cactivityInfo = ChannelTonBingMgr.getActivityInfo();
            if(ActivityMgr.activityInShowTime(cactivityInfo)){
                sendCTonBingChat(msg);
            }
        } else if (msg.getType() == eMessageType.TombUnionInTrapNeedHelp.getValue()) {
            sendUnionChat(player, msg);
        } else if (msg.getType() == eMessageType.TombBossGoDownstairs.getValue()) {
            sendCrossActivityChat(msg);
        } else if (eMessageType.XiuXianPublicChat.getValue() == msg.getType()
                || eMessageType.XiuXianCampChat.getValue() == msg.getType()) {
            sendXiuXianChat(msg);
        }else if (eMessageType.FiveHeroPublicChat.getValue() == msg.getType()
                || eMessageType.FiveHeroCampChat.getValue() == msg.getType()) {
            sendFiveHeroChat(msg);
        } else if (eMessageType.KuangPublicChat.getValue() == msg.getType()
                || eMessageType.KuangCampChat.getValue() == msg.getType()) {
            sendKuangChat(msg);
        } else if (eMessageType.UnionCampWarPublicChat.getValue() == msg.getType()
                || eMessageType.UnionCampWarCampChat.getValue() == msg.getType()) {
            sendUnionCampWarChat(player, msg);
        } else if (eMessageType.JiuZhouRoomChat.getValue() == msg.getType()) {
            sendJiuZhouRoomChat(msg);
        } else if(msg.getType() == eMessageType.CommonTeamChat.getValue()){
            commonTeamChat(player,msg);
        }
    }
    public static void addWorldMessage(String unionUid, WorldMessageProto.WorldMessageTempMsg.Builder msg) {
        if(msg.getType() == eMessageType.OreWarNamingGet.getValue()){
            sendUnionChat(unionUid, msg);
        }else if(msg.getType() == eMessageType.OreWarNamingLose.getValue()){
            sendUnionChat(unionUid, msg);
        }
    }

    private static void sendBanquetChat(WorldMessageProto.WorldMessageTempMsg.Builder msg){
        CrossBanquetProto.CrossBanquetChatReqMsg.Builder reqMsg = CrossBanquetProto.CrossBanquetChatReqMsg.newBuilder();
        reqMsg.setBanquetId(msg.getBanquetId());
        reqMsg.setMsg(msg);
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C_CROSS_PARTY_CHAT, reqMsg);
        GamePlayerMgr.sendPacket(0, pbMsg);
//            BanquetMgr.syncBanquetMemberChatMsg(msg.getBanquetId(), msg);
    }

    public static void sendCrossActivityChat(WorldMessageProto.WorldMessageTempMsg.Builder msg){
        ActivityInfo activityInfo = NormalActivityMgr.getActivityInfo(msg.getActivityId());
        if(null == activityInfo){//活动不在了
            activityInfo = OreWarActivityMgr.getOpenActivityInfo(msg.getActivityId());
        }
        if(null == activityInfo){//活动不在了
            activityInfo = TradeWarActivityMgr.getOpenActivityInfo(msg.getActivityId());
        }
        if (activityInfo == null) {
            activityInfo = StrongholdActivityMgr.getOpenActivityInfo(msg.getActivityId());
        }

        if(null == activityInfo){
            activityInfo = UnionWarActivityMgr.getOpenActivityInfo(msg.getActivityId());
        }

        if(null == activityInfo){
            activityInfo = RelationActivityMgr.getOpenActivityInfo(msg.getActivityId());
        }

        if(null == activityInfo) {
            return;
        }

        CrossActivityProto.CrossActivityChatReqMsg.Builder reqMsg = CrossActivityProto.CrossActivityChatReqMsg.newBuilder();
        reqMsg.setActivityId(msg.getActivityId());
        reqMsg.setMsg(msg);
        reqMsg.setChannelId(ServerListMgr.getChannelId(GameServer.getInstance().getServerId()));
        reqMsg.setSyncChannel(false);
        YanQuMessage pbMsg;
        if(activityInfo.getType() == eActivityType.CrossTradeWarActivity.getValue()){
            pbMsg = YanQuMessageUtils.buildMessage(Protocol.C_CROSS_TRADE_WAR_CHAT, reqMsg);
        }
//        else if(activityInfo.getType() == eActivityType.OreWarActivity.getValue() && activityInfo.getChildType() == eActivityOreWarType.CrossOreWar.getChildType()){
//            pbMsg = YanQuMessageUtils.buildMessage(Protocol.C_CROSS_ORE_WAR_CHAT, reqMsg);
//        }
        else if (ActivityHelper.isCrossChannelActivityType(activityInfo.getType())) { // 跨地区活动：只有瓦舍是本渠道聊天，其余跨地区聊天
            boolean syncChannel = activityInfo.getType() != eActivityType.WasheActivity.getValue();
            reqMsg.setSyncChannel(syncChannel);
            pbMsg = YanQuMessageUtils.buildMessage(Protocol.C3_CROSS_ACTIVITY_CHAT, reqMsg);
        } else if((activityInfo.getType() == eActivityType.CookingBoyActivity.getValue() || activityInfo.getType() == eActivityType.ChefDuel.getValue()) && activityInfo.getChildType() == 2){
            List<Integer> list = ActivityChatMgr.getActivityServerList2ByType(activityInfo.getType());
            if(list.isEmpty()){
                pbMsg = YanQuMessageUtils.buildMessage(Protocol.C_CROSS_ACTIVITY_CHAT, reqMsg);
            }else {
                //多个活动
                for (int aid : list) {
                    WorldMessageProto.WorldMessageTempMsg.Builder builder = reqMsg.getMsg().toBuilder().setActivityId(aid);
                    reqMsg.setMsg(builder);
                    reqMsg.setActivityId(aid);
                    pbMsg = YanQuMessageUtils.buildMessage(Protocol.C_CROSS_ACTIVITY_CHAT, reqMsg.build());
                    GamePlayerMgr.sendPacket(0, pbMsg);
                }
                return;
            }
        } else {
            pbMsg = YanQuMessageUtils.buildMessage(Protocol.C_CROSS_ACTIVITY_CHAT, reqMsg);

        }

        long userId = msg.getUserId();

        boolean groupActivityType = UnionActivityGroupHelper.isGroupActivityType(activityInfo.getType());
        if (groupActivityType) {
            int groupId = GameUnionActivityGroupMgr.getGroupId(activityInfo.getActivityId(), userId);
            msg.setGroupId(groupId);
            reqMsg.setMsg(msg);
            GamePlayerMgr.sendUnionActivityGroupPacket(Protocol.C_CROSS_ACTIVITY_GROUP_CHAT, reqMsg,userId, activityInfo.getActivityId(),groupId );
        }else {
            GamePlayerMgr.sendPacket(0, pbMsg);
        }
    }

    private static void sendCrossBanquetChat(WorldMessageProto.WorldMessageTempMsg.Builder msg){
        UserCrossBanquetData banquetData = CrossBanquetMgr.getBanquet(msg.getBanquetId());
        if(null == banquetData){//宴会过期了不在了
            return;
        }
        CrossBanquetProto.CrossBanquetChatReqMsg.Builder reqMsg = CrossBanquetProto.CrossBanquetChatReqMsg.newBuilder();
        reqMsg.setBanquetId(msg.getBanquetId());
        reqMsg.setMsg(msg);
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C_CROSS_BANQUET_CHAT, reqMsg);
        GamePlayerMgr.sendPacket(0, pbMsg);
    }

    private static void sendCrossGroupChat(WorldMessageProto.WorldMessageTempMsg.Builder msg){
        ServerGroup serverGroup = ServerGroupMgr.getServerGroupByServerId(GameServer.getInstance().getServerId());
        if(null == serverGroup || !serverGroup.isCrossChat()){//跨服聊天未开放
            return;
        }
        //加一下平台每日数据
        try {
            GamePlayer player = GamePlayerMgr.getOnlinePlayer(msg.getUserId());
            if (null != player) {
                player.getModule(XiaoMianModule.class).addCrossChatTimes(1);
            }
        }catch (Exception e){

        }
        //加一下平台每日数据,结束
        CrossGroupProto.CrossGroupChatReqMsg.Builder reqMsg = CrossGroupProto.CrossGroupChatReqMsg.newBuilder();
        reqMsg.setGroupId(serverGroup.getGroupId());
        reqMsg.setMsg(msg);
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C_CROSS_GROUP_CHAT, reqMsg);
        GamePlayerMgr.sendPacket(0, pbMsg);
    }

    private static void sendZhaoShangGroupChat(WorldMessageProto.WorldMessageTempMsg.Builder msg){
        if(!ZsMgr.isZsSystemOpenTime()){
            return;
        }
        int groupId = (int)GameServer.getInstance().getServerId();
        CrossServerGroup serverGroup = CrossServerGroupMgr.getServerGroupByServerId(GameServer.getInstance().getServerId());
        if(null != serverGroup && serverGroup.getCrossZsState() == 1){
            groupId = serverGroup.getGroupId();
        }
        CrossGroupProto.CrossGroupChatReqMsg.Builder reqMsg = CrossGroupProto.CrossGroupChatReqMsg.newBuilder();
        reqMsg.setGroupId(groupId);
        reqMsg.setMsg(msg);
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C_ZHAOSHANG_GROUP_CHAT, reqMsg);
        GamePlayerMgr.sendPacket(0, pbMsg);
    }

    private static void sendTongBingChat(WorldMessageProto.WorldMessageTempMsg.Builder msg) {
        CrossActivityProto.CrossActivityChatReqMsg.Builder reqMsg = CrossActivityProto.CrossActivityChatReqMsg.newBuilder();
        reqMsg.setActivityId(msg.getActivityId());
        reqMsg.setMsg(msg);
        reqMsg.setChannelId(ServerListMgr.getChannelId(GameServer.getInstance().getServerId()));
        reqMsg.setSyncChannel(false);
        int groupId = GameUnionActivityGroupMgr.getGroupId(msg.getActivityId(), msg.getUserId());
        GamePlayerMgr.sendUnionActivityGroupPacket(Protocol.C2_TONG_BING_SEND_CHAT, reqMsg, msg.getUserId(), msg.getActivityId(), groupId);
    }

    private static void sendChuHanChat(WorldMessageProto.WorldMessageTempMsg.Builder msg) {
        CrossActivityProto.CrossActivityChatReqMsg.Builder reqMsg = CrossActivityProto.CrossActivityChatReqMsg.newBuilder();
        reqMsg.setActivityId(msg.getActivityId());
        reqMsg.setMsg(msg);
        reqMsg.setChannelId(ServerListMgr.getChannelId(GameServer.getInstance().getServerId()));
        reqMsg.setSyncChannel(false);
        int groupId = GameUnionActivityGroupMgr.getGroupId(msg.getActivityId(), msg.getUserId());
        GamePlayerMgr.sendUnionActivityGroupPacket(Protocol.C2_CHUHAN_SEND_CHAT, reqMsg, msg.getUserId(), msg.getActivityId(), groupId);
    }

    private static void sendTonBingChat(WorldMessageProto.WorldMessageTempMsg.Builder msg) {
        CrossActivityProto.CrossActivityChatReqMsg.Builder reqMsg = CrossActivityProto.CrossActivityChatReqMsg.newBuilder();
        reqMsg.setActivityId(msg.getActivityId());
        reqMsg.setMsg(msg);
        reqMsg.setChannelId(ServerListMgr.getChannelId(GameServer.getInstance().getServerId()));
        reqMsg.setSyncChannel(false);
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C2_TON_BING_SEND_CHAT, reqMsg);
        GamePlayerMgr.sendPacket(msg.getUserId(), pbMsg);
    }

    private static void sendCTonBingChat(WorldMessageProto.WorldMessageTempMsg.Builder msg) {
        CrossActivityProto.CrossActivityChatReqMsg.Builder reqMsg = CrossActivityProto.CrossActivityChatReqMsg.newBuilder();
        reqMsg.setActivityId(msg.getActivityId());
        reqMsg.setMsg(msg);
        reqMsg.setChannelId(ServerListMgr.getChannelId(GameServer.getInstance().getServerId()));
        reqMsg.setSyncChannel(false);
        GamePlayerMgr.sendChannelPlayerPacketEx(Protocol.N_TON_BING_SEND_CHAT, reqMsg,msg.getUserId());
    }

    private static void sendXiuXianChat(WorldMessageProto.WorldMessageTempMsg.Builder msg) {
        CrossActivityProto.CrossActivityChatReqMsg.Builder reqMsg = CrossActivityProto.CrossActivityChatReqMsg.newBuilder();
        reqMsg.setActivityId(msg.getActivityId());
        reqMsg.setMsg(msg);
        reqMsg.setChannelId(ServerListMgr.getChannelId(GameServer.getInstance().getServerId()));
        reqMsg.setSyncChannel(false);
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C_CROSS_XIU_XIAN_SEND_CHAT, reqMsg);
        GamePlayerMgr.sendPacket(msg.getUserId(), pbMsg);
    }

    private static void sendKuangChat(WorldMessageProto.WorldMessageTempMsg.Builder msg) {
        GamePlayer player = GamePlayerMgr.getOnlinePlayer(msg.getUserId());
        if (null == player) {
            return;
        }
        int matchGroupId = KuangMgr.getMatchGroupId();
        if (matchGroupId == -1) {
            return;
        }
        Kuang.CrossKuangChatReqMsg.Builder reqMsg = Kuang.CrossKuangChatReqMsg.newBuilder();
        reqMsg.setGroupId(matchGroupId);
        reqMsg.setMsg(msg);
        reqMsg.setChannelId(ServerListMgr.getChannelId(GameServer.getInstance().getServerId()));
        reqMsg.setSyncChannel(false);
        player.getModule(KuangModule.class).sendAppointActivityPacket(Protocol.C_CROSS_KUANG_SEND_CHAT, reqMsg);
    }

    private static void sendFiveHeroChat(WorldMessageProto.WorldMessageTempMsg.Builder msg) {
        CrossActivityProto.CrossActivityChatReqMsg.Builder reqMsg = CrossActivityProto.CrossActivityChatReqMsg.newBuilder();
        reqMsg.setActivityId(msg.getActivityId());
        reqMsg.setMsg(msg);
        reqMsg.setChannelId(ServerListMgr.getChannelId(GameServer.getInstance().getServerId()));
        reqMsg.setSyncChannel(false);
        /*YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C2_CROSS_FIVE_HERO_SEND_CHAT, reqMsg);
        GamePlayerMgr.sendChannelPacket(msg.getUserId(), pbMsg);*/
        int groupId = GameUnionActivityGroupMgr.getGroupId(reqMsg.getActivityId(),msg.getUserId());
        GamePlayerMgr.sendUnionActivityGroupPacket(CrossProtocol.C2_CROSS_FIVE_HERO_SEND_CHAT,
                reqMsg,msg.getUserId(),reqMsg.getActivityId(),groupId);
    }

    private static void sendSystemGroupChat(WorldMessageProto.WorldMessageTempMsg.Builder msg){
        CrossGroupProto.SystemCrossGroupChatReqMsg.Builder reqMsg = CrossGroupProto.SystemCrossGroupChatReqMsg.newBuilder();
        reqMsg.setSystemId(msg.getActivityId());
        reqMsg.setMsg(msg);
        if(msg.getActivityId() == eSystemId.NewMonopolyMarket.getValue()){
            int weekId = GameConfig.getSystemThisWeekId();
            SystemServerGroupWeekData weekData = CrossSystemGroupMgr.getSystemServerGroup(weekId, msg.getActivityId());
            if(weekData != null){
                reqMsg.setGroupId(weekData.getGroupId());
                GamePlayerMgr.sendAppointActivityPacket(Protocol.C2_SYSTEM_GROUP_CHAT, reqMsg, msg.getUserId(), weekData.getCrossId(), weekData.getGroupId());
            }
        }else {
            int groupId = SystemCrossServerGroupMgr.getGroupIdByServerId(msg.getActivityId(), GameServer.getInstance().getServerId());
            reqMsg.setGroupId(groupId);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C_SYSTEM_GROUP_CHAT, reqMsg);
            GamePlayerMgr.sendPacket(0, pbMsg);
        }
    }

    public static void sendUnionChat(GamePlayer player, WorldMessageProto.WorldMessageTempMsg.Builder msg) {
        if(StringUtils.isNullOrEmpty(player.getUserInfo().getUnionUid())){
            return;
        }
        CrossUnionProto.UnionMemberChatReqMsg.Builder reqMsg = CrossUnionProto.UnionMemberChatReqMsg.newBuilder();
        reqMsg.setMsg(msg);
        reqMsg.setUnionUid(player.getUserInfo().getUnionUid());
        player.sendPacket(Protocol.C_UNION_MEMBER_CHAT, reqMsg);
//        synchronized (unionMessageMsgMap){
//            if(!unionMessageMsgMap.containsKey(player.getUserInfo().getUnionUid())){
//                unionMessageMsgMap.put(player.getUserInfo().getUnionUid(), new ArrayList<>());
//            }
//            List<WorldMessageProto.WorldMessageTempMsg.Builder> unionMsgList = unionMessageMsgMap.get(player.getUserInfo().getUnionUid());
//            if(unionMsgList.size() >= MAX_MESSAGE_COUNT){
//                unionMsgList.remove(0);
//            }
//            unionMsgList.add(msg);
//        }
//        UnionMgr.syncUnionMemberChatMsg(player.getUserInfo().getUnionUid(), msg);
    }

    public static void sendUnionChat(String toUnionUid, WorldMessageProto.WorldMessageTempMsg.Builder msg) {
        if(StringUtils.isNullOrEmpty(toUnionUid)){
            return;
        }
        CrossUnionProto.UnionMemberChatReqMsg.Builder reqMsg = CrossUnionProto.UnionMemberChatReqMsg.newBuilder();
        reqMsg.setMsg(msg);
        reqMsg.setUnionUid(toUnionUid);
        GamePlayerMgr.sendPacket(0, YanQuMessageUtils.buildMessage(Protocol.C_UNION_MEMBER_CHAT, reqMsg));
//        synchronized (unionMessageMsgMap){
//            if(!unionMessageMsgMap.containsKey(toUnionUid)){
//                unionMessageMsgMap.put(toUnionUid, new ArrayList<>());
//            }
//            List<WorldMessageProto.WorldMessageTempMsg.Builder> unionMsgList = unionMessageMsgMap.get(toUnionUid);
//            if(unionMsgList.size() >= MAX_MESSAGE_COUNT){
//                unionMsgList.remove(0);
//            }
//            unionMsgList.add(msg);
//        }
//        UnionMgr.syncUnionMemberChatMsg(toUnionUid, msg);
    }

    private static void sendWorldMessage(long userId, WorldMessageProto.WorldMessageTempMsg.Builder msg) {
        YanQuMessage packet = YanQuMessageUtils.buildMessage(Protocol.A_WORLD_MESSAGE_TRANSFER, msg);
        ServerLinkControl.send(userId, packet);
    }

    public static void addTask(GeneralTask task) {
        threadTaskManger.addTask(taskId.getAndIncrement(), task);
    }

    /**
     * 用户中心公告
     */
    public static void userCenterMsg(String content) {
        worldNotify(eMessageType.SystemNotice.getValue(), content);
    }

    public static void worldNotify(long userId,UserBaseInfo userBaseInfo, int type, Object... str) {
        String content = encodeContent(str);
        worldNotifyCross(userId,userBaseInfo, type, content);
    }

    public static void worldNotify(GamePlayer player, int type, Object... str) {
        String content = encodeContent(str);
        worldNotify(player, type, content);
    }

    public static void worldNotify(int type, Object... str) {
        String content = encodeContent(str);
        worldNotify(null, type, content);
    }

    /**
     * 发送到agent
     */
    public static void worldNotify(GamePlayer player, int type, String content) {
        if (null == content) {
            return;
        }
        WorldMessageProto.WorldMessageTempMsg.Builder msg = WorldMessageProto.WorldMessageTempMsg.newBuilder();
        msg.setType(type);
        msg.setSendTime(System.currentTimeMillis() / 1000);
        msg.setContent(content);
        if(null != player){
            UserInfo userInfo = player.getUserInfo();
            msg.setUserId(player.getUserId());
            PlayerProto.PlayerBaseTempMsg.Builder baseMsg = PlayerPb.parsePlayerBaseTempMsg(userInfo);
            msg.setPlayerBaseData(baseMsg);
        }
        addWorldMessageMsgToList(0, msg);
    }

    //跨服下来的没有player
    public static void worldNotifyCross(long userId,UserBaseInfo userBaseInfo, int type, String content) {
        if (StringUtils.isNullOrEmpty(content)) {
            return;
        }
        WorldMessageProto.WorldMessageTempMsg.Builder msg = WorldMessageProto.WorldMessageTempMsg.newBuilder();
        msg.setUserId(userId);
        msg.setType(type);
        msg.setSendTime(System.currentTimeMillis() / 1000);
        msg.setContent(content);
        PlayerProto.PlayerBaseTempMsg.Builder baseMsg = PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo);
        msg.setPlayerBaseData(baseMsg);
        addWorldMessageMsgToList(0, msg);
    }

    //谨慎加，系统消息才往这里发
    public static void addWorldMessageMsgToList(long sendUserId, WorldMessageProto.WorldMessageTempMsg.Builder msg){
        if(eMessageType.WorldChat.getValue() == msg.getType() || msg.getType() == eMessageType.WingRoomWorldShare.getValue()) {
            synchronized (worldMessageMsgList) {
                if (worldMessageMsgList.size() >= MAX_WORLD_MESSAGE_COUNT) {
                    worldMessageMsgList.remove(0);
                }
                worldMessageMsgList.add(msg);
            }
            addWorldMessage(msg);
        }else {
            //系统消息也上跨服
            long serverId = ConfigHelper.getLong("serverId");
            if(CrossUnionServerGroupMgr.getGroupServerCountByServerId(serverId) > 1 && msg.getType() != eMessageType.BanquetOpenNotice.getValue()){
                //如果是开启跨服商会分组，则发送到系统分组聊天频道
                CrossGroupProto.SystemCrossGroupChatReqMsg.Builder reqMsg = CrossGroupProto.SystemCrossGroupChatReqMsg.newBuilder();
                reqMsg.setSystemId(eSystemId.Union.getValue());
                int groupId = CrossUnionServerGroupMgr.getGroupIdByServerId(GameServer.getInstance().getServerId());
                reqMsg.setGroupId(groupId);
                reqMsg.setMsg(msg);
                YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C_CROSS_WORLD_SYSTEM_MESSAGE_ADD, reqMsg);
                GamePlayerMgr.sendPacket(sendUserId, pbMsg);
                return;
            }
            synchronized (systemMessageMsgList) {
                if (systemMessageMsgList.size() >= MAX_MESSAGE_COUNT) {
                    systemMessageMsgList.remove(0);
                }
                systemMessageMsgList.add(msg);
            }
        }
        sendWorldMessage(sendUserId, msg);
    }

    public static void changeWorldMessageContent(long sendUserId, int type, String content, long startTime) {
        synchronized (worldMessageMsgList) {
            for (WorldMessageProto.WorldMessageTempMsg.Builder builder : worldMessageMsgList) {
                if (builder.getType() == type && builder.getUserId() == sendUserId && builder.getSendTime() > startTime / 1000) {
                    builder.setContent(content);
                }
            }
        }
        synchronized (worldMessageMap) {
            for (WorldMessage message : worldMessageMap.values()) {
                if (message.getType() == type && message.getUserId() == sendUserId && message.getSendTime() > startTime / 1000) {
                    message.setContent(content);
                }
            }
        }
    }

    public static void changeUnionMessageContent(long sendUserId, int type, String content, long startTime, String shareUnionUid) {
        UserInfo userInfo = UserMgr.getUserInfo(sendUserId);
        if (userInfo == null || StringUtils.isNullOrEmpty(shareUnionUid) || CrossUnionMgr.getUnionInfo(shareUnionUid) == null) {
            return;
        }
        WingRoomProto.ChangeUnionShareMessageStatusMsg.Builder builder = WingRoomProto.ChangeUnionShareMessageStatusMsg.newBuilder();
        builder.setUserId(sendUserId);
        builder.setType(type);
        builder.setContent(content);
        builder.setStartTime(startTime);
        builder.setUnionUid(shareUnionUid);
        GamePlayerMgr.sendPacket(0, YanQuMessageUtils.buildMessage(Protocol.C_UNION_CHANGE_CHAT_MESSAGE, builder));
    }

    private static void addWorldMessage(WorldMessageProto.WorldMessageTempMsg.Builder msg){
        if(null != msg){
            synchronized (worldMessageMap){
                int index = msgIndex % MAX_WORLD_MESSAGE_COUNT;
                WorldMessage worldMessage = worldMessageMap.get(index);
                if(null == worldMessage){
                    worldMessage = new WorldMessage();
                    worldMessage.setIndex(index);
                    worldMessage.setInsertOption();
                    worldMessageMap.put(worldMessage.getIndex(), worldMessage);
                }
                worldMessage.setType(msg.getType());
                worldMessage.setContentType(msg.getContentType());
                worldMessage.setSendTime(msg.getSendTime());
                worldMessage.setContent(msg.getContent());
                worldMessage.setUserId(msg.getUserId());
                msgIndex = index + 1;
            }
        }
    }

    public static String encodeContent(Object ... strings) {
        StringBuilder content = new StringBuilder();
        if (strings != null) {
            for (Object str : strings) {
                content.append(str).append(SEPARATOR);
            }
        }
        if(content.length() > 0){
            return content.substring(0, content.length() - SEPARATOR.length());
        }
        return content.toString();
    }

    /**
     * 获取聊天任务类型
     * @param player
     * @param type
     * @param contentType
     * @param content
     * @param activityId
     * @param banquetId
     * @param time
     * @return
     */
    public static GeneralTask getChatTask(GamePlayer player, int type, int contentType, String content, int activityId, String banquetId, long time, List<String> callUserNameList, String groupParam, boolean showIp) {
        int channelId = ServerListMgr.getServerInfo(GameServer.getInstance().getServerId()).getChannelId();
        if (eChannelType.isMainLandChannel(channelId)) {
          return new ChatTask(player, type, contentType, content, activityId,banquetId, time, true, true, true, callUserNameList, groupParam, showIp);
        } else if (channelId == eChannelType.InnerChannel.getValue() || channelId == eChannelType.JapanInnerTest.getValue() || channelId == eChannelType.KoreaInnerTest.getValue() || channelId == eChannelType.VNInnerTest.getValue() || channelId == eChannelType.ThailandInnerTest.getValue() || channelId == eChannelType.MainLandInnerTest.getValue()) {
            return new InnerWoldChatTask(player, type, contentType, content, activityId,banquetId, time, callUserNameList, groupParam, showIp);
        } else if (channelId == eChannelType.MainLand.getValue() || channelId == eChannelType.MainLandTest.getValue() || channelId == eChannelType.MainLandBusiness.getValue()) {
            return new WoldChatTask(player, type, contentType, content, activityId,banquetId, time, callUserNameList, groupParam, showIp);
        } else {
            return new ChatTask(player, type, contentType, content, activityId,banquetId, time, true, false, true, callUserNameList, groupParam, showIp);
        }
    }

    private static boolean isMainLandChannel(int channelId) {
        Set<Integer> channelIdSet = new HashSet<>();
        channelIdSet.add(eChannelType.MainLand.getValue());
        channelIdSet.add(eChannelType.MainLandTest.getValue());
        channelIdSet.add(eChannelType.MainLandBusiness.getValue());
        channelIdSet.add(eChannelType.XiaoChengXu.getValue());
        channelIdSet.add(eChannelType.XiaoChengXuTest.getValue());
        channelIdSet.add(eChannelType.XiaoChengXuInnerTest.getValue());
        return channelIdSet.contains(channelId);
    }

    private static void sendCrossMarriageGroupChat(WorldMessageProto.WorldMessageTempMsg.Builder msg){
        CrossMarriageGroup marriageGroup = CrossMarriageGroupMgr.getCrossMarriageGroupByServerId(GameServer.getInstance().getServerId());
        if(null != marriageGroup && (marriageGroup.isCrossMarriage() || marriageGroup.isCrossBanquet())){
            CrossGroupProto.CrossGroupChatReqMsg.Builder reqMsg = CrossGroupProto.CrossGroupChatReqMsg.newBuilder();
            reqMsg.setGroupId(marriageGroup.getGroupId());
            reqMsg.setMsg(msg);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C_MARRIAGE_GROUP_CHAT, reqMsg);
            GamePlayerMgr.sendPacket(0, pbMsg);
        }
    }

    public static void sendDunHuangShiKuTeamChat(GamePlayer player,WorldMessageProto.WorldMessageTempMsg.Builder msg){
        DunHuangShiKuProto.DunHuangShiKuTeamChatReqMsg.Builder req = DunHuangShiKuProto.DunHuangShiKuTeamChatReqMsg.newBuilder();
        req.setActivityId(msg.getActivityId());
        req.setMsg(msg);
        player.sendUnionActivityGroupPacket(CrossProtocol.C2_DUN_HUANG_SHI_KU_TEAM_CHAT, req, req.getActivityId());
    }

    public static void sendDouLuoDaLuTeamChat(GamePlayer player,WorldMessageProto.WorldMessageTempMsg.Builder msg){
        DouLuoDaLuProto.DouLuoDaLuTeamChatReqMsg.Builder req = DouLuoDaLuProto.DouLuoDaLuTeamChatReqMsg.newBuilder();
        req.setActivityId(msg.getActivityId());
        req.setMsg(msg);
        player.sendUnionActivityGroupPacket(Protocol.C_DOU_LUO_DA_LU_TEAM_CHAT, req, req.getActivityId());
    }

    /**
     * 通用组队-发送聊天
     * @param player
     * @param msg
     */
    public static void commonTeamChat(GamePlayer player, WorldMessageProto.WorldMessageTempMsg.Builder msg){
        CommonTeamProto.CommonTeamSendChatReqMsg.Builder req = CommonTeamProto.CommonTeamSendChatReqMsg.newBuilder();
        req.setActivityId(msg.getActivityId());
        req.setMsg(msg);
//        player.sendPacket(Protocol.C2_COMMON_TEAM_SEND_CHAT_MSG, req);
        player.sendUnionActivityGroupPacket(CrossProtocol.C2_COMMON_TEAM_SEND_CHAT_MSG, req, req.getActivityId());
    }

    public static void sendUnionCampWarChat(GamePlayer player,WorldMessageProto.WorldMessageTempMsg.Builder msg){
        player.sendPacket(Protocol.C3_UNION_CAMP_WAR_CHAT, msg);
    }

    public static boolean isContentForbidden(String content, long chatTime){
        int sameCount = 0;
        long queryTime = chatTime - (GameConfig.CHAT_LIMIT_INTERVAL_TIME * 1000);
        List<WorldMessageProto.WorldMessageTempMsg.Builder> listMsg = getWorldMessageMsgList();
        if(listMsg.size() > 0){
            for(int i = listMsg.size() - 1; i >= 0; i--){
                WorldMessageProto.WorldMessageTempMsg.Builder data = listMsg.get(i);
                if(data.getSendTime() * 1000 < queryTime){
                    break;
                }
                if(Objects.equals(data.getContent(), content)){
                    sameCount++;
                }
            }
        }
        return sameCount >= GameConfig.CHAT_LIMIT_SAME_CONTENT_COUNT - 1;
    }

    /**
     * 九州聊天室
     */
    private static void sendJiuZhouRoomChat(WorldMessageProto.WorldMessageTempMsg.Builder msg) {
        CrossActivityProto.CrossActivityChatReqMsg.Builder reqMsg = CrossActivityProto.CrossActivityChatReqMsg.newBuilder();
        reqMsg.setActivityId(JiuZhouMgr.getConfig().getActivityId());
        reqMsg.setMsg(msg);
        reqMsg.setChannelId(ServerListMgr.getChannelId(GameServer.getInstance().getServerId()));
        reqMsg.setSyncChannel(false);
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C_CROSS_JIU_ZHOU_SEND_ROOM_CHAT, reqMsg);
        GamePlayerMgr.sendPacket(msg.getUserId(), pbMsg);
    }

}
